import 'package:flutter/material.dart';
import '../../models/fishing_king.dart';

class FishingKingPage extends StatefulWidget {
  const FishingKingPage({super.key});

  @override
  State<FishingKingPage> createState() => _FishingKingPageState();
}

class _FishingKingPageState extends State<FishingKingPage> with TickerProviderStateMixin {
  late TabController _tabController;
  
  // 模拟数据
  final List<FishingKing> _weeklyRanking = [
    FishingKing(
      id: 1,
      userName: '钓鱼大师',
      avatar: 'https://mypond.tos-cn-guangzhou.volces.com/202508/bc96f40d-162d-49e5-b966-f98c773d0695_avatar',
      totalCatch: 156,
      totalWeight: 89.5,
      biggestFish: 8500,
      biggestFishType: '草鱼',
      rank: 1,
      points: 2580,
      location: '西湖',
      lastCatchTime: DateTime.now().subtract(const Duration(hours: 2)),
      badges: ['周冠军', '巨物王', '连竿达人'],
    ),
    FishingKing(
      id: 2,
      userName: '渔夫老王',
      avatar: 'https://mypond.tos-cn-guangzhou.volces.com/202508/bc96f40d-162d-49e5-b966-f98c773d0695_avatar',
      totalCatch: 142,
      totalWeight: 76.3,
      biggestFish: 7200,
      biggestFishType: '鲤鱼',
      rank: 2,
      points: 2340,
      location: '钱塘江',
      lastCatchTime: DateTime.now().subtract(const Duration(hours: 5)),
      badges: ['技术流', '早起鸟'],
    ),
    FishingKing(
      id: 3,
      userName: '江边钓客',
      avatar: 'https://mypond.tos-cn-guangzhou.volces.com/202508/bc96f40d-162d-49e5-b966-f98c773d0695_avatar',
      totalCatch: 128,
      totalWeight: 68.9,
      biggestFish: 6800,
      biggestFishType: '青鱼',
      rank: 3,
      points: 2150,
      location: '明经',
      lastCatchTime: DateTime.now().subtract(const Duration(hours: 8)),
      badges: ['坚持者', '夜钓王'],
    ),
    FishingKing(
      id: 4,
      userName: '钓友小李',
      avatar: 'https://mypond.tos-cn-guangzhou.volces.com/202508/bc96f40d-162d-49e5-b966-f98c773d0695_avatar',
      totalCatch: 115,
      totalWeight: 62.1,
      biggestFish: 5900,
      biggestFishType: '鲫鱼',
      rank: 4,
      points: 1980,
      location: '欢乐',
      lastCatchTime: DateTime.now().subtract(const Duration(hours: 12)),
      badges: ['新星', '勤奋者'],
    ),
    FishingKing(
      id: 5,
      userName: '野钓达人',
      avatar: 'https://mypond.tos-cn-guangzhou.volces.com/202508/bc96f40d-162d-49e5-b966-f98c773d0695_avatar',
      totalCatch: 98,
      totalWeight: 55.7,
      biggestFish: 5200,
      biggestFishType: '鲈鱼',
      rank: 5,
      points: 1750,
      location: '野河',
      lastCatchTime: DateTime.now().subtract(const Duration(days: 1)),
      badges: ['野钓专家'],
    ),
  ];

  final List<FishingKing> _monthlyRanking = [
    FishingKing(
      id: 1,
      userName: '钓鱼大师',
      avatar: 'https://mypond.tos-cn-guangzhou.volces.com/202508/bc96f40d-162d-49e5-b966-f98c773d0695_avatar',
      totalCatch: 658,
      totalWeight: 356.8,
      biggestFish: 12500,
      biggestFishType: '青鱼',
      rank: 1,
      points: 12580,
      location: '西湖',
      lastCatchTime: DateTime.now().subtract(const Duration(hours: 2)),
      badges: ['月度冠军', '巨物王', '连竿达人', '技术流'],
    ),
    FishingKing(
      id: 6,
      userName: '钓场老板',
      avatar: 'https://mypond.tos-cn-guangzhou.volces.com/202508/bc96f40d-162d-49e5-b966-f98c773d0695_avatar',
      totalCatch: 589,
      totalWeight: 298.5,
      biggestFish: 9800,
      biggestFishType: '草鱼',
      rank: 2,
      points: 11240,
      location: '明经',
      lastCatchTime: DateTime.now().subtract(const Duration(hours: 1)),
      badges: ['月亚军', '稳定发挥'],
    ),
    FishingKing(
      id: 2,
      userName: '渔夫老王',
      avatar: 'https://mypond.tos-cn-guangzhou.volces.com/202508/bc96f40d-162d-49e5-b966-f98c773d0695_avatar',
      totalCatch: 542,
      totalWeight: 276.3,
      biggestFish: 8900,
      biggestFishType: '鲤鱼',
      rank: 3,
      points: 10340,
      location: '钱塘江',
      lastCatchTime: DateTime.now().subtract(const Duration(hours: 5)),
      badges: ['月季军', '技术流', '早起鸟'],
    ),
  ];

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 2, vsync: this);
  }

  @override
  void dispose() {
    _tabController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.grey[50],
      appBar: AppBar(
        title: const Text(
          '钓王榜',
          style: TextStyle(
            fontWeight: FontWeight.bold,
            color: Colors.white,
          ),
        ),
        backgroundColor: Colors.blue[600],
        elevation: 0,
        iconTheme: const IconThemeData(color: Colors.white),
        bottom: TabBar(
          controller: _tabController,
          labelColor: Colors.white,
          unselectedLabelColor: Colors.white70,
          indicatorColor: Colors.white,
          indicatorWeight: 3,
          tabs: const [
            Tab(text: '周榜'),
            Tab(text: '月榜'),
          ],
        ),
      ),
      body: TabBarView(
        controller: _tabController,
        children: [
          _buildRankingList(_weeklyRanking, '本周'),
          _buildRankingList(_monthlyRanking, '本月'),
        ],
      ),
    );
  }

  Widget _buildRankingList(List<FishingKing> rankings, String period) {
    return RefreshIndicator(
      onRefresh: () async {
        // 模拟刷新
        await Future.delayed(const Duration(seconds: 1));
      },
      child: ListView.builder(
        padding: const EdgeInsets.all(16),
        itemCount: rankings.length + 1, // +1 for header
        itemBuilder: (context, index) {
          if (index == 0) {
            return _buildHeader(period);
          }
          
          final king = rankings[index - 1];
          return _buildRankingCard(king);
        },
      ),
    );
  }

  Widget _buildHeader(String period) {
    return Container(
      margin: const EdgeInsets.only(bottom: 16),
      padding: const EdgeInsets.all(20),
      decoration: BoxDecoration(
        gradient: LinearGradient(
          colors: [Colors.blue[600]!, Colors.blue[800]!],
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
        ),
        borderRadius: BorderRadius.circular(16),
        boxShadow: [
          BoxShadow(
            color: Colors.blue.withOpacity(0.3),
            blurRadius: 10,
            offset: const Offset(0, 4),
          ),
        ],
      ),
      child: Column(
        children: [
          Row(
            children: [
              Icon(
                Icons.emoji_events,
                color: Colors.amber[300],
                size: 32,
              ),
              const SizedBox(width: 12),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      '$period钓王榜',
                      style: const TextStyle(
                        color: Colors.white,
                        fontSize: 20,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    const SizedBox(height: 4),
                    Text(
                      '展示$period钓获量最多的钓友',
                      style: TextStyle(
                        color: Colors.white.withOpacity(0.9),
                        fontSize: 14,
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
          const SizedBox(height: 16),
          Row(
            children: [
              Expanded(
                child: _buildStatItem('参与人数', '${_weeklyRanking.length}+', Icons.people),
              ),
              Container(
                width: 1,
                height: 40,
                color: Colors.white.withOpacity(0.3),
              ),
              Expanded(
                child: _buildStatItem('总钓获', '1000+条', Icons.phishing),
              ),
              Container(
                width: 1,
                height: 40,
                color: Colors.white.withOpacity(0.3),
              ),
              Expanded(
                child: _buildStatItem('总重量', '500+kg', Icons.monitor_weight),
              ),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildStatItem(String label, String value, IconData icon) {
    return Column(
      children: [
        Icon(icon, color: Colors.white, size: 20),
        const SizedBox(height: 4),
        Text(
          value,
          style: const TextStyle(
            color: Colors.white,
            fontSize: 16,
            fontWeight: FontWeight.bold,
          ),
        ),
        Text(
          label,
          style: TextStyle(
            color: Colors.white.withOpacity(0.8),
            fontSize: 12,
          ),
        ),
      ],
    );
  }

  Widget _buildRankingCard(FishingKing king) {
    return Container(
      margin: const EdgeInsets.only(bottom: 12),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(16),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.05),
            blurRadius: 10,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: InkWell(
        onTap: () => _showKingDetail(king),
        borderRadius: BorderRadius.circular(16),
        child: Padding(
          padding: const EdgeInsets.all(16),
          child: Row(
            children: [
              // 排名
              _buildRankBadge(king.rank),
              const SizedBox(width: 16),
              
              // 头像
              Container(
                width: 60,
                height: 60,
                decoration: BoxDecoration(
                  shape: BoxShape.circle,
                  border: Border.all(
                    color: _getRankColor(king.rank),
                    width: 3,
                  ),
                ),
                child: ClipOval(
                  child: Image.network(
                    king.avatar,
                    fit: BoxFit.cover,
                    errorBuilder: (context, error, stackTrace) {
                      return Container(
                        color: Colors.grey[300],
                        child: Icon(
                          Icons.person,
                          color: Colors.grey[600],
                          size: 30,
                        ),
                      );
                    },
                  ),
                ),
              ),
              const SizedBox(width: 16),
              
              // 用户信息
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      children: [
                        Expanded(
                          child: Text(
                            king.userName,
                            style: const TextStyle(
                              fontSize: 16,
                              fontWeight: FontWeight.bold,
                            ),
                            overflow: TextOverflow.ellipsis,
                            maxLines: 1,
                          ),
                        ),
                        Container(
                          padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                          decoration: BoxDecoration(
                            color: Colors.orange[100],
                            borderRadius: BorderRadius.circular(12),
                          ),
                          child: Text(
                            '${king.points}分',
                            style: TextStyle(
                              color: Colors.orange[800],
                              fontSize: 12,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                        ),
                      ],
                    ),
                    const SizedBox(height: 8),
                    
                    // 徽章
                    if (king.badges.isNotEmpty)
                      Wrap(
                        spacing: 4,
                        children: king.badges.take(2).map((badge) => Container(
                          padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
                          decoration: BoxDecoration(
                            color: _getRankColor(king.rank).withOpacity(0.1),
                            borderRadius: BorderRadius.circular(8),
                          ),
                          child: Text(
                            badge,
                            style: TextStyle(
                              color: _getRankColor(king.rank),
                              fontSize: 10,
                              fontWeight: FontWeight.w500,
                            ),
                          ),
                        )).toList(),
                      ),
                    const SizedBox(height: 8),
                    
                    // 统计信息
                    Wrap(
                      spacing: 8,
                      runSpacing: 4,
                      children: [
                        _buildStatChip(Icons.phishing, '${king.totalCatch}条'),
                        _buildStatChip(Icons.monitor_weight, '${king.totalWeight.toStringAsFixed(1)}kg'),
                        _buildStatChip(Icons.location_on, king.location),
                      ],
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildRankBadge(int rank) {
    Color color;
    IconData icon;
    
    switch (rank) {
      case 1:
        color = Colors.amber;
        icon = Icons.looks_one;
        break;
      case 2:
        color = Colors.grey[400]!;
        icon = Icons.looks_two;
        break;
      case 3:
        color = Colors.orange[700]!;
        icon = Icons.looks_3;
        break;
      default:
        color = Colors.blue[600]!;
        icon = Icons.emoji_events;
    }

    return Container(
      width: 40,
      height: 40,
      decoration: BoxDecoration(
        color: color,
        shape: BoxShape.circle,
        boxShadow: [
          BoxShadow(
            color: color.withOpacity(0.3),
            blurRadius: 8,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: rank <= 3 
        ? Icon(icon, color: Colors.white, size: 24)
        : Center(
            child: Text(
              '$rank',
              style: const TextStyle(
                color: Colors.white,
                fontSize: 16,
                fontWeight: FontWeight.bold,
              ),
            ),
          ),
    );
  }

  Widget _buildStatChip(IconData icon, String text) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
      decoration: BoxDecoration(
        color: Colors.grey[100],
        borderRadius: BorderRadius.circular(8),
      ),
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          Icon(icon, size: 12, color: Colors.grey[600]),
          const SizedBox(width: 2),
          Flexible(
            child: Text(
              text,
              style: TextStyle(
                fontSize: 10,
                color: Colors.grey[700],
              ),
              overflow: TextOverflow.ellipsis,
              maxLines: 1,
            ),
          ),
        ],
      ),
    );
  }

  Color _getRankColor(int rank) {
    switch (rank) {
      case 1:
        return Colors.amber;
      case 2:
        return Colors.grey[400]!;
      case 3:
        return Colors.orange[700]!;
      default:
        return Colors.blue[600]!;
    }
  }

  void _showKingDetail(FishingKing king) {
    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      backgroundColor: Colors.transparent,
      builder: (context) => Container(
        height: MediaQuery.of(context).size.height * 0.7,
        decoration: const BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
        ),
        child: Column(
          children: [
            // 拖拽指示器
            Container(
              margin: const EdgeInsets.only(top: 8),
              width: 40,
              height: 4,
              decoration: BoxDecoration(
                color: Colors.grey[300],
                borderRadius: BorderRadius.circular(2),
              ),
            ),
            
            // 内容
            Expanded(
              child: Padding(
                padding: const EdgeInsets.all(20),
                child: Column(
                  children: [
                    // 头像和基本信息
                    Row(
                      children: [
                        Container(
                          width: 80,
                          height: 80,
                          decoration: BoxDecoration(
                            shape: BoxShape.circle,
                            border: Border.all(
                              color: _getRankColor(king.rank),
                              width: 4,
                            ),
                          ),
                          child: ClipOval(
                            child: Image.network(
                              king.avatar,
                              fit: BoxFit.cover,
                              errorBuilder: (context, error, stackTrace) {
                                return Container(
                                  color: Colors.grey[300],
                                  child: Icon(
                                    Icons.person,
                                    color: Colors.grey[600],
                                    size: 40,
                                  ),
                                );
                              },
                            ),
                          ),
                        ),
                        const SizedBox(width: 16),
                        Expanded(
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Text(
                                king.userName,
                                style: const TextStyle(
                                  fontSize: 24,
                                  fontWeight: FontWeight.bold,
                                ),
                              ),
                              const SizedBox(height: 4),
                              Row(
                                children: [
                                  _buildRankBadge(king.rank),
                                  const SizedBox(width: 8),
                                  Text(
                                    '第${king.rank}名',
                                    style: TextStyle(
                                      fontSize: 16,
                                      color: Colors.grey[600],
                                    ),
                                  ),
                                ],
                              ),
                            ],
                          ),
                        ),
                      ],
                    ),
                    
                    const SizedBox(height: 24),
                    
                    // 徽章
                    if (king.badges.isNotEmpty) ...[
                      Align(
                        alignment: Alignment.centerLeft,
                        child: Text(
                          '荣誉徽章',
                          style: TextStyle(
                            fontSize: 16,
                            fontWeight: FontWeight.bold,
                            color: Colors.grey[800],
                          ),
                        ),
                      ),
                      const SizedBox(height: 8),
                      Wrap(
                        spacing: 8,
                        runSpacing: 8,
                        children: king.badges.map((badge) => Container(
                          padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
                          decoration: BoxDecoration(
                            color: _getRankColor(king.rank).withOpacity(0.1),
                            borderRadius: BorderRadius.circular(16),
                            border: Border.all(
                              color: _getRankColor(king.rank).withOpacity(0.3),
                            ),
                          ),
                          child: Text(
                            badge,
                            style: TextStyle(
                              color: _getRankColor(king.rank),
                              fontSize: 12,
                              fontWeight: FontWeight.w500,
                            ),
                          ),
                        )).toList(),
                      ),
                      const SizedBox(height: 24),
                    ],
                    
                    // 详细统计
                    Expanded(
                      child: GridView.count(
                        crossAxisCount: 2,
                        crossAxisSpacing: 16,
                        mainAxisSpacing: 16,
                        childAspectRatio: 1.5,
                        children: [
                          _buildDetailCard('总钓获', '${king.totalCatch}条', Icons.phishing, Colors.blue),
                          _buildDetailCard('总重量', '${king.totalWeight.toStringAsFixed(1)}kg', Icons.monitor_weight, Colors.green),
                          _buildDetailCard('最大鱼', '${(king.biggestFish / 1000).toStringAsFixed(1)}kg', Icons.trending_up, Colors.orange),
                          _buildDetailCard('积分', '${king.points}分', Icons.star, Colors.purple),
                        ],
                      ),
                    ),
                    
                    // 其他信息
                    Container(
                      padding: const EdgeInsets.all(16),
                      decoration: BoxDecoration(
                        color: Colors.grey[50],
                        borderRadius: BorderRadius.circular(12),
                      ),
                      child: Column(
                        children: [
                          Row(
                            children: [
                              Icon(Icons.location_on, color: Colors.grey[600], size: 16),
                              const SizedBox(width: 8),
                              Expanded(
                                child: Text(
                                  '常钓地点：${king.location}',
                                  overflow: TextOverflow.ellipsis,
                                  maxLines: 1,
                                ),
                              ),
                            ],
                          ),
                          const SizedBox(height: 8),
                          Row(
                            children: [
                              Icon(Icons.access_time, color: Colors.grey[600], size: 16),
                              const SizedBox(width: 8),
                              Expanded(
                                child: Text(
                                  '最后钓获：${_formatTime(king.lastCatchTime)}',
                                  overflow: TextOverflow.ellipsis,
                                  maxLines: 1,
                                ),
                              ),
                            ],
                          ),
                          const SizedBox(height: 8),
                          Row(
                            children: [
                              Icon(Icons.pets, color: Colors.grey[600], size: 16),
                              const SizedBox(width: 8),
                              Expanded(
                                child: Text(
                                  '最大鱼种：${king.biggestFishType}',
                                  overflow: TextOverflow.ellipsis,
                                  maxLines: 1,
                                ),
                              ),
                            ],
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildDetailCard(String title, String value, IconData icon, Color color) {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: color.withOpacity(0.1),
        borderRadius: BorderRadius.circular(12),
        border: Border.all(color: color.withOpacity(0.3)),
      ),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(icon, color: color, size: 32),
          const SizedBox(height: 8),
          Text(
            value,
            style: TextStyle(
              fontSize: 18,
              fontWeight: FontWeight.bold,
              color: color,
            ),
          ),
          Text(
            title,
            style: TextStyle(
              fontSize: 12,
              color: Colors.grey[600],
            ),
          ),
        ],
      ),
    );
  }

  String _formatTime(DateTime time) {
    final now = DateTime.now();
    final difference = now.difference(time);
    
    if (difference.inMinutes < 60) {
      return '${difference.inMinutes}分钟前';
    } else if (difference.inHours < 24) {
      return '${difference.inHours}小时前';
    } else {
      return '${difference.inDays}天前';
    }
  }
}